<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.cake.libs.controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

/**
 * This is a placeholder class.
 * Create the same file in app/app_controller.php
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       cake
 * @subpackage    cake.cake.libs.controller
 * @link http://book.cakephp.org/view/957/The-App-Controller
 */
class AppController extends Controller {
		var $components = array('RequestHandler','Acl','Breadcrumb','Auth','DebugKit.Toolbar','Session','Cookie');
		var $helpers = array('Session', 'Html' , 'Form', 'Time','Javascript','Js','Ajax');  
	
	/*function beforeFilter() {
		parent::beforeFilter(); 
		$this->Auth->allow(array('*'));

		//Configure AuthComponent
		$this->Auth->authorize = 'actions';
		$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
		$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
		$this->Auth->loginRedirect = array('controller' => 'news', 'action' => 'add');
	}
	*/
	function beforeFilter() {
		parent::beforeFilter(); 
		$this->Auth->allow('*');
		$this->Auth->authorize = 'actions';
		$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
		$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
		$this->set('loginIn', $this->Auth->user());
		$this->Auth->loginRedirect = '/news/';      
		$this->Auth->actionPath = 'controllers/';
	}
	function beforeRender(){
	
		$layout_setting = $this->layout;
		if($layout_setting != 'default'){
		   $this->set('breadcrumb', $this->Breadcrumb->setBreadcrumb($this->params['url']['url']));
			$this->set('show_all_categories',$this->app_show_all_categories());	
			$this->set('show_all_news',$this->app_show_all_news());	
			$this->set('show_menu',$this->show_menu());
		}
	}
	
	//Show all category
	function app_show_all_categories(){
		$this->loadModel('Category');
		return $this->Category->generatetreelist(null, null, null, '__');
	}
	
	//Get_user by id
	function get_user_by_id($user_id = null){
		$this->loadModel('User');
		$result =  $this->User->read(null,$user_id);
		if(isset($result['User'])){
			return $result['User'];
		}
		return null;
	}
	/*Menu
	--------------------*/
	function show_menu($limit_cat = null){
		$this->loadModel('Category');
		$this->Category->recursive = 0;
		$categories =  $this->Category->find('all');
		$get_list_pretn_menus = array();
		$str_menu = '';
		if($categories){
			$i=0;
			foreach ($categories as $category){
				if(empty($category['Category']['parent_id'])){
					$get_list_pretn_menus[$i] = $category['Category'];
					$i++;
				}
			}
			
			if(!empty($get_list_pretn_menus)){
				$j= 0;
				foreach($get_list_pretn_menus as $get_list_pretn_menu){
					$i= 0;
					foreach($categories as $category){
						if(!empty($category['Category']['parent_id']) && $get_list_pretn_menu['id'] == $category['Category']['parent_id']) {
							$get_list_pretn_menus[$j]['Child'][$i] = $category['Category'];
							$i++;
						}
						
					}
					$j++;
				}
				foreach($get_list_pretn_menus as $set_parent){
					$str_menu .= '<li class="cat-item cat-item-'.$set_parent['id'].'"><a href="'.$this->webroot.'news/category/'.$set_parent['id'].'">'.$set_parent['name'].'</a>';
					if(isset($set_parent['Child']) && $set_parent['Child'] != null){
						$str_menu .= '<ul class="children">';
							foreach($set_parent['Child'] as $set_child){
								$str_menu .= '<li class="cat-item cat-item-'.$set_child['id'].'"><a href="'.$this->webroot.'news/category/'.$set_child['id'].'">'.$set_child['name'].'</a></li>';
							}
						$str_menu .= '</ul>';
					}
					$str_menu .= '</li>';
				}
			}
		}
		$str_menu .= '<li class="cat-item cat-item-706"><a href="'.$this->webroot.'videos/show/">Video Youtube</a></li>';
		return $str_menu;
		
	}
	function create_menu($cats = null,$paren_id = null){
	
	}
	 // function to parse a video <entry>
    function parseVideoEntry($entry) {      
      $obj= new stdClass;
      
      // get author name and feed URL
      $obj->author = $entry->author->name;
      $obj->authorURL = $entry->author->uri;
      
      // get nodes in media: namespace for media information
      $media = $entry->children('http://search.yahoo.com/mrss/');
      $obj->title = $media->group->title;
      $obj->description = $media->group->description;
      
      // get video player URL
      $attrs = $media->group->player->attributes();
      $obj->watchURL = $attrs['url']; 
      
      // get video thumbnail
      $attrs = $media->group->thumbnail[0]->attributes();
      $obj->thumbnailURL = $attrs['url']; 
            
      // get <yt:duration> node for video length
      $yt = $media->children('http://gdata.youtube.com/schemas/2007');
      $attrs = $yt->duration->attributes();
      $obj->length = $attrs['seconds']; 
      
      // get <yt:stats> node for viewer statistics
      $yt = $entry->children('http://gdata.youtube.com/schemas/2007');
      $attrs = $yt->statistics->attributes();
      $obj->viewCount = $attrs['viewCount']; 
      
      // get <gd:rating> node for video ratings
      $gd = $entry->children('http://schemas.google.com/g/2005'); 
      if ($gd->rating) { 
        $attrs = $gd->rating->attributes();
        $obj->rating = $attrs['average']; 
      } else {
        $obj->rating = 0;         
      }
        
      // get <gd:comments> node for video comments
      $gd = $entry->children('http://schemas.google.com/g/2005');
      if ($gd->comments->feedLink) { 
        $attrs = $gd->comments->feedLink->attributes();
        $obj->commentsURL = $attrs['href']; 
        $obj->commentsCount = $attrs['countHint']; 
      }
      
      // get feed URL for video responses
      $entry->registerXPathNamespace('feed', 'http://www.w3.org/2005/Atom');
      $nodeset = $entry->xpath("feed:link[@rel='http://gdata.youtube.com/schemas/2007#video.responses']"); 
      if (count($nodeset) > 0) {
        $obj->responsesURL = $nodeset[0]['href'];      
      }
         
      // get feed URL for related videos
      $entry->registerXPathNamespace('feed', 'http://www.w3.org/2005/Atom');
      $nodeset = $entry->xpath("feed:link[@rel='http://gdata.youtube.com/schemas/2007#video.related']"); 
      if (count($nodeset) > 0) {
        $obj->relatedURL = $nodeset[0]['href'];      
      }
    
      // return object to caller  
      return $obj;      
    }  
	function get_cat_limit_data($cat = null, $limit = null){
		$this->loadModel('News');
		$data = $this->News->find('all',array(
			'conditions' => array(
				'News.category_id' => $cat
			)
		));
		$i =0;
		if($cat == null)
			$cat = 1;
		if($limit == null)
			$limit = 10;		
		$results = array();
		foreach($data as $set_data){
			if( $i < $limit){
				$results[$i] = $set_data;
				$i++;
			}// 
		}
		return $results;
	}
	//Get_comment by new_id
	function get_comment_by_new_id($new_id = null){
		$this->loadModel('Comment');
		$result =  $this->Comment->find('all',array(
			'condition'=>array(
				'Comment.user_id'=> $new_id
			)
		));
		$get_all_comments = array();
		if(isset($result)){
			foreach($get_all_comments as $get_all_comment){
				$get_all_comments[] = $get_all_comment['Comment'];
			}
			return $get_all_comments;
		}
		return null;
	}
		//Show all category
	function app_show_all_news(){
		$this->loadModel('News');
		$get_all_news =   $this->News->find('all',array(
			'condition' => array(
				'News.status' => '1'
			),
			'fields' => array(
				'News.id',
				'News.name',
				'News.created',
				'News.modified'
			)
		));
		$set_lists = array();
		$i=0;
		if(!empty($get_all_news)){
			foreach($get_all_news as $get_all_new){
				$k = date("Y-m",strtotime($get_all_new['News']['created']));
				$t = 'On '.date("m, Y",strtotime($get_all_new['News']['created']));
				if(!in_array($t,$set_lists)){
					$set_lists[$k] = $t;
				}
			}
		}
		$set_lists_new = array();
		
		return $set_lists_new;
	}
	/**
	* uploads image of product to the server
	* @params:
	*              $folder         = the folder to upload the files e.g. 'img/uploads'
	*              $formdata       = the array containing the form files
	*              $itemId         = id of the item (optional) will create a new sub folder
	* @return:
	*              will return an array with the success of each file upload
	*/
	/**
	* AppController::uploadFiles()
	* 
	* @return
	*/
	function uploadFiles($folder, $formdata, $itemId = null) {
		// setup dir names absolute and relative
		$folder_url = WWW_ROOT.$folder;
		$rel_url = $folder;

		// create the folder if it does not exist
		if(!is_dir($folder_url)) {
				mkdir($folder_url);
		}

		// if itemId is set create an item folder
				if($itemId) {
				// set new absolute folder
				$folder_url = WWW_ROOT.$folder.'/'.$itemId; 
				// set new relative folder
				$rel_url = $folder.'/'.$itemId;
				// create directory
				if(!is_dir($folder_url)) {
						mkdir($folder_url);
				}
		}
		// list of permitted file types, this is only images but documents can be added  
		$permitted = array('image/jpg','image/gif','image/jpeg','image/pjpeg','image/png');
		// loop through and deal with the files
		//foreach($formdata as $file) {
				$file = $formdata;
				//var_dump($formdata);
				//die();
				// replace spaces with underscores
				$filename = str_replace(' ', '_', $file['name']);
				// assume filetype is false
				$typeOK = false;
				// check filetype is ok
				foreach($permitted as $type) {
				//$type = 'application/octet-stream';
						if($type == $file['type']) {
								$typeOK = true;
								break;
						}
				}

				if($typeOK) {
				// switch based on error code
						switch($file['error']) {
						case 0:
								// check filename already exists
								if(!file_exists($folder_url.'/'.$filename)) {
										// create full filename
										$full_url = $folder_url.'/'.$filename;
										$url = $rel_url.'/'.$filename;
										//$url = $filename;
										// upload the file
										$success = move_uploaded_file($file['tmp_name'], $url);
								} else {
										// create unique filename and upload file
										ini_set('date.timezone', 'Europe/London');
										$now = date('Y-m-d-His');
										$full_url = $folder_url.'/'.$now.$filename;
										$url = $rel_url.'/'.$now.$filename;
										//$url = $now.$filename;
										//$save_image=$now.$filename;
										$success = move_uploaded_file($file['tmp_name'], $url);
								}
								// if upload was successful
								if($success) {
										// save the url of the file
										$result['urls'][] = $url;
								} else {
										$result['errors'][] = "Error uploaded $filename. Please try again.";
								}
								break;
						case 3:
								// an error occured
								$result['errors'][] = "Error uploading $filename. Please try again.";
								break;
						default:
								// an error occured
								$result['errors'][] = "System error uploading $filename. Contact webmaster.";
								break;
						}
				} elseif($file['error'] == 4) {
						// no file was selected for upload
						$result['nofiles'][] = "No file Selected";
				} else {
						// unacceptable file type
						//if (substr($filename, -4) == '.zip')
								//$result['errors'][] = "$filename cannot be uploaded. Please try again";
						//else
								$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: jpg,gif,jpeg,png";
				}
		//}

		return $result;
		
	}
	
	function the_excerpt_max_charlength($content = null ,$charlength = null ) {
	   $content = trim(get_the_excerpt());
	   $charlength++;
	   $results = '';
	   if(strlen($content)>$charlength) {
		
		   $subex = substr($content,0,$charlength-5);
		   $exwords = explode(" ",$subex);
		   $excut = -(strlen($exwords[count($exwords)-1]));
		   if($excut<0) {
				$results.= substr($subex,0,$excut);
		   } else {
				$results.= $subex;
		   }
		   $results.= "...";
	   } else {
		  $results.= $content;
	   }
	   return $results;
	}

}

